package com.hmall.item.Intercepter;
import com.hmall.item.commone.BaseContext;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@Component
public class LoginIntercepter implements HandlerInterceptor {

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String authorization = request.getHeader("authorization");

        String requestURI = request.getRequestURI();

        System.out.println("拦截器到请求:"+requestURI);

        // 在拦截器中获取请求头中的authorization信息
        if (authorization == null || "".equals(authorization)) {
            return false;
        }

        // 2代表用户2
        if ("2".equals(authorization)){
            Long userId  = Long.parseLong(authorization);
            // 将userId保存到ThreadLocal中
            BaseContext.setCurrentId(userId);
            System.out.println("请求头中存在authorization："+userId);
            System.out.println("-------------------------------放行-------------------------------");
            return true;
        }

        return false;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        System.out.println("提交拦截");
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        System.out.println("拦截后");
    }
}
